﻿angular.module('Caltech')
    .directive('csvDownload', function (Constants, $document, $timeout, Restangular, moment) {
        'use strict';

        return {
            restrict: 'A',
            scope: {
                data: '=csvDownload',
                filename: '@filename',
                headers: '@csvHeaders'
            },
            controller: function ($scope, Restangular) {
                $scope.export = function (data) {
                    var result = new CSV(data, { header: true }).encode(),
                        downloadLink = angular.element('<a></a>'),
                        blob = new Blob([result]);

                    downloadLink.attr('href', window.URL.createObjectURL(blob));
                    downloadLink.attr('download', $scope.filename || 'export.csv');

                    $document.find('body').append(downloadLink);

                    $timeout(function () {
                        downloadLink[0].click();
                        downloadLink.remove();
                    });
                };
            },
            link: function (scope, element, attrs) {
                element.on('click', function () {
                    var data = Restangular.stripRestangular(scope.data),
                        result;

                    if (scope.headers) {
                        var result = new Array(data.length);

                        angular.forEach(JSON.parse(scope.headers.replace(/\'/g, '"')), function (sourceName, destName) {
                            data.forEach(function (item, index) {
                                var value = item[sourceName];

                                if (!result[index]) {
                                    result[index] = {};
                                }

                                if (sourceName.indexOf('Date') > -1) {
                                    value = moment(value).format('DD/MMM/YYYY');
                                }
                                result[index][destName] = value;
                            });
                        });
                    } else {
                        result = data.map(function (item) {
                            delete item.$$hashKey;
                            return item;
                        });
                    }

                    scope.export(result);
                });
            }
        }
    })
    .directive('csvImport', function () {
        'use strict';

        return {

        };
    });
